package com.alibaba.algo.apiimpl.feign;

import com.alibaba.algo.cooperation.common.BaseResult;
import com.alibaba.algo.cooperation.feign.service.RoleFeignService;
import com.alibaba.algo.cooperation.feign.vo.req.*;
import com.alibaba.algo.cooperation.feign.vo.res.*;
import com.alibaba.algo.cooperation.usercenter.GlobalResultStatus;
import com.alibaba.algo.cooperation.usercomponent.vo.req.user.SelectRoleListRequestVO;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.SelectRoleListResponseVO;
import com.alibaba.algo.core.base.PagerEntity;
import com.alibaba.algo.core.exception.BaseException;
import com.alibaba.algo.domain.user.*;
import com.alibaba.algo.dtos.user.SysOrgDTO;
import com.alibaba.algo.dtos.user.SysRoleUserDTO;
import com.alibaba.algo.entity.user.SysOrg;
import com.alibaba.algo.entity.user.SysRole;
import com.alibaba.algo.entity.user.SysUser;
import com.alibaba.algo.exception.BaseErrorCode;
import com.alibaba.algo.exception.SysRoleErrorCode;
import com.alibaba.algo.util.StringUtil;
import com.alibaba.algo.utils.ConverterUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Fan.tianpeng
 * @date 2021/5/8 14:44
 */
@RestController
@Slf4j
public class RoleFeignServiceImpl implements RoleFeignService {

    @Autowired
    private SysUserRoleDomain sysUserRoleDomain;

    @Autowired
    private SysRoleDomain sysRoleDomain;

    @Autowired
    private SysUserDomain sysUserDomain;

    @Autowired
    private SysOrgDomain sysOrgDomain;

    @Autowired
    private SysOrgRoleDomain sysOrgRoleDomain;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<UserRoleInfoResVO>> qryRoleListByUserIdAndApp(SelectUserRoleByAppReqVO vo) {
        if (ObjectUtils.isEmpty(vo.getUserId()) && ObjectUtils.isEmpty(vo.getEmployeeCode()) && ObjectUtils.isEmpty(vo.getUserAccount())) {
            log.error("OrgFeignServiceImpl qryRoleListByUserIdAndApp params are null.");
            return BaseResult.buildError(BaseErrorCode.USER_ID_AND_EMPLOYEE_CODE_AND_ACCOUNT_IS_NULL.getCode(), BaseErrorCode.USER_ID_AND_EMPLOYEE_CODE_AND_ACCOUNT_IS_NULL.getMessage());
        }
        if (ObjectUtils.isEmpty(vo.getAppCode())) {
            log.error("OrgFeignServiceImpl qryRoleListByUserIdAndApp params are null.");
            return BaseResult.buildError(BaseErrorCode.APP_CODE_IS_NULL.getCode(), BaseErrorCode.APP_CODE_IS_NULL.getMessage());
        }
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap.put("su.id", "desc");
        List<UserRoleInfoResVO> list = sysUserRoleDomain.selectRoleListByUserIdAndApp(vo.getUserId(), vo.getEmployeeCode(), vo.getUserAccount(), vo.getAppCode(), sortMap);
        return BaseResult.buildSuccess(list);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<com.alibaba.algo.cooperation.common.PagerEntity<FeignRoleListResponseVO>> selectPageWithIsDeleted(FeignSelectRoleListRequestVO roleVo) {
        SelectRoleListRequestVO vo = new SelectRoleListRequestVO();
        BeanUtils.copyProperties(roleVo, vo);
        PagerEntity<SelectRoleListResponseVO> pagerEntity = sysRoleDomain.selectPageWithIsDeleted(vo);
        List<SelectRoleListResponseVO> dataList = pagerEntity.getDataList();
        List<FeignRoleListResponseVO> feignDatas = ConverterUtil.getInstance().mapAsList(dataList, FeignRoleListResponseVO.class);
        com.alibaba.algo.cooperation.common.PagerEntity<FeignRoleListResponseVO> feignPage
                = ConverterUtil.getInstance().map(pagerEntity, com.alibaba.algo.cooperation.common.PagerEntity.class);
        feignPage.setDataList(feignDatas);
        return BaseResult.buildSuccess(feignPage);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<com.alibaba.algo.cooperation.common.PagerEntity<FeignRoleListResponseVO>> selectPage(FeignSelectRoleListRequestVO roleVo) {
        SelectRoleListRequestVO vo = new SelectRoleListRequestVO();
        BeanUtils.copyProperties(roleVo, vo);
        PagerEntity<SelectRoleListResponseVO> pagerEntity = sysRoleDomain.selectPage(vo);
        List<SelectRoleListResponseVO> dataList = pagerEntity.getDataList();
        List<FeignRoleListResponseVO> feignDatas = ConverterUtil.getInstance().mapAsList(dataList, FeignRoleListResponseVO.class);
        com.alibaba.algo.cooperation.common.PagerEntity<FeignRoleListResponseVO> feignPage
                = ConverterUtil.getInstance().map(pagerEntity, com.alibaba.algo.cooperation.common.PagerEntity.class);
        feignPage.setDataList(feignDatas);
        return BaseResult.buildSuccess(feignPage);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<RoleInfoResVO>> qryRoleListByApp(FeignSelectRoleListByAppReqVO vo) {
        SysRole sysRole = new SysRole();
        sysRole.setAppCode(vo.getAppCode());
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap.put("id", "desc");
        List<SysRole> sysRoleList = sysRoleDomain.listByPara(sysRole, sortMap);
        List<RoleInfoResVO> resVOList = new ArrayList<>();
        sysRoleList.forEach(s -> {
            RoleInfoResVO resVO = new RoleInfoResVO();
            resVO.setRoleId(s.getId());
            resVO.setRoleName(s.getRoleName());
            resVOList.add(resVO);
        });
        return BaseResult.buildSuccess(resVOList);
    }

    /**
     * 获取⽤户⻆⾊列表（过时）
     *
     * @param vo 用户标识
     * @return 用户角色列表
     */
    @Deprecated
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<UserRoleInfoResVO>> qryRoleListByUserId(SelectUserRoleReqVO vo) {
        if (ObjectUtils.isEmpty(vo.getUserId()) && ObjectUtils.isEmpty(vo.getEmployeeCode()) && ObjectUtils.isEmpty(vo.getUserAccount())) {
            log.error("OrgFeignServiceImpl qryRoleListByUserId params are null.");
            return BaseResult.buildError(BaseErrorCode.USER_ID_AND_EMPLOYEE_CODE_AND_ACCOUNT_IS_NULL.getCode(), BaseErrorCode.USER_ID_AND_EMPLOYEE_CODE_AND_ACCOUNT_IS_NULL.getMessage());
        }
        Long userId = getUserIdByCondition(vo.getUserId(), vo.getEmployeeCode(), vo.getUserAccount());
        if (!ObjectUtils.isEmpty(userId)) {
            LinkedHashMap<String, Object> sortMap = new LinkedHashMap<>();
            sortMap.put("su.id", "desc");
            List<UserRoleInfoResVO> list = sysUserRoleDomain.selectRoleListByUserId(userId, null ,sortMap);
            return BaseResult.buildSuccess(list);
        } else {
            log.error("RoleFeignService qryRoleListByUserId user is not exist.Params are:{}", vo);
            return BaseResult.buildSuccess(Collections.emptyMap());
        }
    }

    /**
     * 根据⻆⾊id或者获取⽤户列表
     *
     * @param vo 角色标识
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<RoleUserInfoResVO>> qryUserListByRoleId(SelectRoleUserReqVO vo) {
        if (ObjectUtils.isEmpty(vo.getRoleId())) {
            throw new BaseException(BaseErrorCode.ROLE_ID_IS_NULL.getCode(), BaseErrorCode.ROLE_ID_IS_NULL.getMessage());
        }
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap.put("ur.id", "desc");
        List<RoleUserInfoResVO> list = sysUserRoleDomain.selectUserListByRoleId(vo.getRoleId(), sortMap);
        return BaseResult.buildSuccess(list);
    }

    /**
     * 根据⻆⾊id或者获取⽤户列表，支持全量查询
     *
     * @param vo 角色标识
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<RoleUserInfoResVO>> qryUserListWithIsDeletedByRoleId(SelectRoleUserReqVO vo) {
        if (ObjectUtils.isEmpty(vo.getRoleId())) {
            throw new BaseException(BaseErrorCode.ROLE_ID_IS_NULL.getCode(), BaseErrorCode.ROLE_ID_IS_NULL.getMessage());
        }
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap.put("ur.id", "desc");
        List<RoleUserInfoResVO> list = sysUserRoleDomain.selectUserListWithIsDeletedByRoleId(vo.getRoleId(), sortMap, vo.getIsDeleted());
        return BaseResult.buildSuccess(list);
    }

    /**
     * 根据⻆⾊id获取⽤户列表附带组织信息
     *
     * @param vo 角色标识
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<RoleUserInfoResVO>> qryUserListWithOrgsByRoleId(SelectRoleUserReqVO vo) {
        if (ObjectUtils.isEmpty(vo.getRoleId())) {
            throw new BaseException(BaseErrorCode.ROLE_ID_IS_NULL.getCode(), BaseErrorCode.ROLE_ID_IS_NULL.getMessage());
        }
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap.put("ur.id", "desc");
        List<RoleUserInfoResVO> list = sysUserRoleDomain.selectUserListWithOrgsByRoleId(vo.getRoleId(), sortMap);
        if(!ObjectUtils.isEmpty(list)){
            list.forEach(item -> {
                String orgIds = item.getOrgIdStrs();
                if(StringUtils.isNotEmpty(orgIds)){
                    if(orgIds.contains(",")){
                        item.setOrgIdList(Arrays.asList(orgIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
                    }else{
                        List<Long> orgIdList = new ArrayList<>();
                        orgIdList.add(Long.parseLong(orgIds));
                        item.setOrgIdList(orgIdList);
                    }
                }
            });
        }
        return BaseResult.buildSuccess(list);
    }

    @Override
    public BaseResult<List<RoleUserInfoResVO>> qryUserListWithOrgByRoleAndOrg(@RequestBody SelectRoleUserReqVO vo){
        if ((null == vo.getRoleId() || vo.getRoleId() <= 0) && StringUtils.isEmpty(vo.getRoleCode())) {
            throw new BaseException(SysRoleErrorCode.ROLE_ID_AND_ROLE_CODE_IS_NULL.getCode(), SysRoleErrorCode.ROLE_ID_AND_ROLE_CODE_IS_NULL.getMessage());
        }
        Set<Long> ids = new HashSet<>();
        //根据组织code或id集合查询组织信息
        if (!(ObjectUtils.isEmpty(vo.getOrgIds()) && ObjectUtils.isEmpty(vo.getOrgCodeList()))) {
            List<SysOrg> orgList = sysOrgDomain.qryOrgListByIdsAndCodes(vo);
            if(!ObjectUtils.isEmpty(orgList)){
                for(SysOrg sysOrg : orgList){
                    ids.add(sysOrg.getId());
                }
            }else{
                vo.setMatchFlag(1);
            }
        }
        //根据组织id查询子组织集合
        if(!ObjectUtils.isEmpty(ids)){
            for(Long orgId : ids){
                List<SysOrg> sysOrgs = sysOrgDomain.qryChildListByOrgId(String.valueOf(orgId));
                if(!ObjectUtils.isEmpty(sysOrgs)){
                    for(SysOrg org : sysOrgs){
                        ids.add(org.getId());
                    }
                }
            }
        }
        vo.setOrgIds(new ArrayList<>(ids));
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<>();
        sortMap.put("ur.id", "desc");
        List<RoleUserInfoResVO> list = sysUserRoleDomain.selectUserListWithOrgByRoleAndOrgs(vo,sortMap);
        if(!ObjectUtils.isEmpty(list)){
            list.forEach(item -> {
                String orgIds = item.getOrgIdStrs();
                if(StringUtils.isNotEmpty(orgIds)){
                    if(orgIds.contains(",")){
                        item.setOrgIdList(Arrays.asList(orgIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
                    }else{
                        List<Long> orgIdList = new ArrayList<>();
                        orgIdList.add(Long.parseLong(orgIds));
                        item.setOrgIdList(orgIdList);
                    }
                }
                String orgCodes = item.getOrgCodeStrs();
                if(StringUtils.isNotEmpty(orgCodes)){
                    if(orgCodes.contains(",")){
                        item.setOrgCodeList(Arrays.asList(orgCodes.split(",")).stream().collect(Collectors.toList()));
                    }else{
                        List<String> orgCodeList = new ArrayList<>();
                        orgCodeList.add(orgCodes);
                        item.setOrgCodeList(orgCodeList);
                    }
                }
            });
        }
        return BaseResult.buildSuccess(list);
    }

    @Override
    public BaseResult<List<RoleUserInfoResVO>> qryUserListWithOrgsByCondition(@RequestBody SelectRoleUserReqVO vo){
        if ((null == vo.getRoleId() || vo.getRoleId() <= 0) && StringUtils.isEmpty(vo.getRoleCode())) {
            throw new BaseException(SysRoleErrorCode.ROLE_ID_AND_ROLE_CODE_IS_NULL.getCode(), SysRoleErrorCode.ROLE_ID_AND_ROLE_CODE_IS_NULL.getMessage());
        }
        Set<Long> ids = new HashSet<>();
        //根据组织code或id集合查询组织信息
        if (!(ObjectUtils.isEmpty(vo.getOrgIds()) && ObjectUtils.isEmpty(vo.getOrgCodeList()))) {
            List<SysOrg> orgList = sysOrgDomain.qryOrgListByIdsAndCodes(vo);
            if(!ObjectUtils.isEmpty(orgList)){
                for(SysOrg sysOrg : orgList){
                    ids.add(sysOrg.getId());
                }
            }else{
                vo.setMatchFlag(1);
            }
        }
        //根据组织id查询子组织集合
        if(!ObjectUtils.isEmpty(ids)){
            List<Long> idsList = new ArrayList<>(ids);
            ListIterator<Long> it = idsList.listIterator();
            while(it.hasNext()){
                Long orgId = it.next();
                List<SysOrg> sysOrgs = sysOrgDomain.qryChildListByOrgId(String.valueOf(orgId));
                if(!ObjectUtils.isEmpty(sysOrgs)){
                    for(SysOrg org : sysOrgs){
                        it.add(org.getId());
                    }
                }
            }
            ids.addAll(idsList);
        }
        vo.setOrgIds(new ArrayList<>(ids));
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<>();
        sortMap.put("ur.id", "desc");
        List<RoleUserInfoResVO> list = sysUserRoleDomain.selectUserListWithOrgByRoleAndOrgs(vo,sortMap);
        Set<String> employeeCodeSet = new HashSet<>();
        if(!ObjectUtils.isEmpty(list)){
            list.forEach(item -> {
                String orgIds = item.getOrgIdStrs();
                if(StringUtils.isNotEmpty(orgIds)){
                    if(orgIds.contains(",")){
                        item.setOrgIdList(Arrays.stream(orgIds.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
                    }else{
                        List<Long> orgIdList = new ArrayList<>();
                        orgIdList.add(Long.parseLong(orgIds));
                        item.setOrgIdList(orgIdList);
                    }
                }
                String orgCodes = item.getOrgCodeStrs();
                if(StringUtils.isNotEmpty(orgCodes)){
                    if(orgCodes.contains(",")){
                        item.setOrgCodeList(Arrays.stream(orgCodes.split(",")).collect(Collectors.toList()));
                    }else{
                        List<String> orgCodeList = new ArrayList<>();
                        orgCodeList.add(orgCodes);
                        item.setOrgCodeList(orgCodeList);
                    }
                }
                employeeCodeSet.add(item.getEmployeeCode());
            });
        }
        if(!ObjectUtils.isEmpty(employeeCodeSet)){
            List<String> employeeCodes = new ArrayList<>(employeeCodeSet);
            List<SysOrgDTO> sysOrgList = sysOrgDomain.selectOrgListByEmployeeCodesAndOrgIds(employeeCodes,new ArrayList<>(ids),vo.getMatchFlag());
            Map<String, List<SysOrgDTO>> orgMap = sysOrgList.stream().collect(Collectors.groupingBy(SysOrgDTO::getEmployeeCode));
            if(!ObjectUtils.isEmpty(list) && !ObjectUtils.isEmpty(orgMap)){
                for(RoleUserInfoResVO item : list){
                    List<SysOrgVO> sysOrgs = new ArrayList<>();
                    List<SysOrgDTO> sysOrgDTOList = orgMap.get(item.getEmployeeCode());
                    if(!ObjectUtils.isEmpty(sysOrgDTOList)){
                        for(SysOrgDTO sysOrgDTO : sysOrgDTOList){
                            SysOrgVO sysOrgVO = new SysOrgVO();
                            BeanUtils.copyProperties(sysOrgDTO,sysOrgVO);
                            sysOrgs.add(sysOrgVO);
                        }
                    }
                    item.setSysOrgList(sysOrgs);
                }
            }
        }
        return BaseResult.buildSuccess(list);
    }

    /**
     * 根据⻆⾊id获取⽤户列表附带主组织信息
     *
     * @param vo 角色标识
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<RoleUserInfoResVO>> qryUserListWithPrimaryOrgByRoleIdAndOrgIds(SelectRoleUserReqVO vo) {
        if (null == vo.getRoleId() || vo.getRoleId() <= 0) {
            throw new BaseException(BaseErrorCode.ROLE_ID_IS_NULL.getCode(), BaseErrorCode.ROLE_ID_IS_NULL.getMessage());
        }
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap.put("ur.id", "desc");
        List<RoleUserInfoResVO> list = sysUserRoleDomain.selectUserListWithPrimaryOrgByRoleAndOrgs(vo.getRoleId(),vo.getOrgIds(), sortMap);
        if(!ObjectUtils.isEmpty(list)){
            list.forEach(item -> {
                String orgIds = item.getOrgIdStrs();
                if(StringUtils.isNotEmpty(orgIds)){
                    if(orgIds.contains(",")){
                        item.setOrgIdList(Arrays.stream(orgIds.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
                    }else{
                        List<Long> orgIdList = new ArrayList<>();
                        orgIdList.add(Long.parseLong(orgIds));
                        item.setOrgIdList(orgIdList);
                    }
                }
            });
        }
        return BaseResult.buildSuccess(list);
    }

    /**
     * 根据⻆⾊id或者角色code获取⽤户列表
     *
     * @param vo 角色标识
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<UserInfoResVO>> qryUserListByRole(GetRoleUserReqVO vo) {
        if (vo.empty()) {
            return BaseResult.buildError(-1, "roleId、roleCode、roleIdList和roleCodeList至少传一个。");
        }
        if (!StringUtil.isEmpty(vo.getRoleCode())) {
            if (vo.getRoleCode().length() > 128) {
                return BaseResult.buildError(-1, "roleCode的长度不允许超过128。");
            }
        }
        List<UserInfoResVO> list = sysRoleDomain.getUsersByRole(vo);
        return BaseResult.buildSuccess(list);
    }

    /**
     * 根据⻆⾊id或者角色code获取⽤户列表,支持全量查询
     *
     * @param vo 角色标识
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<UserInfoResVO>> qryUserListWithIsDeletedByRole(GetRoleUserReqVO vo) {
        if (vo.empty()) {
            return BaseResult.buildError(-1, "roleId、roleCode、roleIdList和roleCodeList至少传一个。");
        }
        if (!StringUtil.isEmpty(vo.getRoleCode())) {
            if (vo.getRoleCode().length() > 128) {
                return BaseResult.buildError(-1, "roleCode的长度不允许超过128。");
            }
        }
        List<UserInfoResVO> list = sysRoleDomain.getUsersWithIsDeletedByRole(vo);
        return BaseResult.buildSuccess(list);
    }

    /**
     * 根据⻆⾊id列表获取⽤户列表
     *
     * @param
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<RpcUserInfoVO>> selectUserListByRoleIdListOrAppCodeList(SelectUserListByRoleIdListReqVO vo) {
        if (vo == null) {
            throw new BaseException(BaseErrorCode.ROLEID_OR_APPCODE_LIST_IS_NULL_OR_EMPTY.getCode(), BaseErrorCode.ROLEID_OR_APPCODE_LIST_IS_NULL_OR_EMPTY.getMessage());
        }
        if ((vo.getRoleIdList() == null || vo.getRoleIdList().isEmpty()) && (vo.getAppCode() == null)) {
            throw new BaseException(BaseErrorCode.ROLEID_OR_APPCODE_LIST_IS_NULL_OR_EMPTY.getCode(), BaseErrorCode.ROLEID_OR_APPCODE_LIST_IS_NULL_OR_EMPTY.getMessage());
        }
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap.put("ur.id", "desc");
        List<RpcUserInfoVO> list = sysUserRoleDomain.selectUserListByRoleIdListOrAppCodeList(vo, sortMap);
        return BaseResult.buildSuccess(list);
    }


    /**
     * 获取全量角色列表（过时）
     *
     * @return 角色列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<RoleInfoResVO>> qryRoleList() {
        SysRole sysRole = new SysRole();
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<>();
        sortMap.put("id", "desc");
        List<SysRole> sysRoleList = sysRoleDomain.listByPara(sysRole, sortMap);
        List<RoleInfoResVO> resVOList = new ArrayList<>();
        sysRoleList.forEach(s -> {
            RoleInfoResVO resVO = new RoleInfoResVO();
            resVO.setRoleId(s.getId());
            resVO.setRoleName(s.getRoleName());
            resVOList.add(resVO);
        });
        return BaseResult.buildSuccess(resVOList);
    }

    private Long getUserIdByCondition(Long userId, String employeeCode, String userAccount) {
        SysUser sysUser = null;
        // 用户信息
        if (!ObjectUtils.isEmpty(userId)) {
            sysUser = sysUserDomain.getById(userId);
        } else if (!ObjectUtils.isEmpty(employeeCode)) {
            sysUser = sysUserDomain.getOneByEmployeeCode(employeeCode);
        } else if (!ObjectUtils.isEmpty(userAccount)) {
            sysUser = sysUserDomain.getByUserAccount(userAccount);
        }
        if (!ObjectUtils.isEmpty(sysUser) && !ObjectUtils.isEmpty(sysUser.getId())) {
            return sysUser.getId();
        } else {
            log.error("RoleFeignService getUserIdByCondition user is not exist.Params are:userId:{},employeeCode:{},userAccount:{}", userId, employeeCode, userAccount);
            return null;
        }
    }

    @Override
    public BaseResult selectRolePageByOrgCondition(@RequestBody SelectRoleByOrgVO vo) {
        if (null == vo) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (ObjectUtils.isEmpty(vo.getPageIndex()) || vo.getPageIndex() < 0) {
            throw new BaseException(BaseErrorCode.PAGE_INDEX_IS_NULL.getCode(), BaseErrorCode.PAGE_INDEX_IS_NULL.getMessage());
        }
        if (ObjectUtils.isEmpty(vo.getPageSize()) || vo.getPageSize() <= 0) {
            throw new BaseException(BaseErrorCode.PAGE_SIZE_IS_NULL.getCode(), BaseErrorCode.PAGE_SIZE_IS_NULL.getMessage());
        }
        if (ObjectUtils.isEmpty(vo.getOrgIds()) && null == vo.getOrgCode()) {
            throw new BaseException(BaseErrorCode.ORG_ID_AND_ORG_CODE_IS_NULL.getCode(), BaseErrorCode.ORG_ID_AND_ORG_CODE_IS_NULL.getMessage());
        }
        List<Long> orgIds = vo.getOrgIds();
        //根据组织code获取组织
        if (!ObjectUtils.isEmpty(vo.getOrgCode())) {
            List<SysOrg> sysOrgList = sysOrgDomain.qryOrgListByOrgCode(vo.getOrgCode());
            if (!ObjectUtils.isEmpty(sysOrgList)) {
                List<Long> ids = sysOrgList.stream().map(SysOrg::getId).collect(Collectors.toList());
                //合并id集合
                if (!ObjectUtils.isEmpty(orgIds)) {
                    orgIds = Stream.of(ids, orgIds).flatMap(Collection::stream).distinct().collect(Collectors.toList());
                } else {
                    orgIds = ids;
                }
            }
        }
        List<SysRole> roleList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(orgIds)) {
            //根据组织id查询其子组织
            String orgIdsStr = orgIds.parallelStream().map(String::valueOf).collect(Collectors.joining(","));
            List<Long> ids = sysOrgDomain.qryOrgIdListByOrgId(orgIdsStr);
            ids = Stream.of(ids, orgIds).flatMap(Collection::stream).distinct().collect(Collectors.toList());
            vo.setOrgIds(ids);
            //根据组织查询关联的角色
            PageHelper.startPage(vo.getPageIndex(), vo.getPageSize());
            roleList = sysOrgRoleDomain.selectRoleListByOrgCondition(vo);
        }
        PageInfo<SysRole> pageInfo = new PageInfo<>(roleList);
        return BaseResult.buildSuccess(pageInfo);
    }

    /**
     * 根据用户信息查询角色列表
     *
     * @param vo 用户信息
     * @return 角色列表
     */
    @Override
    public BaseResult<com.alibaba.algo.cooperation.common.PagerEntity<RoleInfoResponseVO>> selectRoleListByUser(SelectRoleListByUserReqVO vo) {
        // 检查参数正确性
        if (null == vo) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (ObjectUtils.isEmpty(vo.getPageSize())) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getMsg());
        }
        if (vo.getPageSize() > 10) {
            throw new BaseException(GlobalResultStatus.PARAM_PAGE_SIZE_OVERSIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_OVERSIZE_ERROR.getMsg());
        }

        // 分页查询符合条件的岗位列表
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<>();
        sortMap = ObjectUtils.isEmpty(vo.getSortMap()) ? sortMap : vo.getSortMap();
        SysRole roleCon = new SysRole();
        BeanUtils.copyProperties(vo, roleCon);
        com.alibaba.algo.core.base.PagerEntity pagerEntity = sysRoleDomain.pageByPara(roleCon, vo.getPageIndex(), vo.getPageSize(), sortMap);
        List<SysRole> sysRoleList = (List<SysRole>) pagerEntity.getDataList();
        List<RoleInfoResponseVO> roleInfoResponseVOList = new ArrayList<>(sysRoleList.size());
        for (SysRole tmpRole : sysRoleList) {
            RoleInfoResponseVO tmpRoleInfoResponseVO = new RoleInfoResponseVO();
            BeanUtils.copyProperties(tmpRole, tmpRoleInfoResponseVO);
            tmpRoleInfoResponseVO.setRoleId(tmpRole.getId());
            tmpRoleInfoResponseVO.setUserList(new ArrayList<>());
            roleInfoResponseVOList.add(tmpRoleInfoResponseVO);
        }
        com.alibaba.algo.cooperation.common.PagerEntity<RoleInfoResponseVO> newPagerEntity = new com.alibaba.algo.cooperation.common.PagerEntity(pagerEntity.getTotal(), pagerEntity.getTotalPages(), pagerEntity.getPageSize(), pagerEntity.getPageIndex(), roleInfoResponseVOList);
        if (CollectionUtils.isEmpty(pagerEntity.getDataList())) {
            return BaseResult.buildSuccess(newPagerEntity);
        }

        // 查询处理人员信息
        //获取组织ID清单
        List<Long> qryList = new ArrayList<>(newPagerEntity.getDataList().size());
        for (RoleInfoResponseVO item : newPagerEntity.getDataList()) {
            qryList.add(item.getRoleId());
        }
        GetRoleUserReqVO getRoleUserReqVO = new GetRoleUserReqVO();
        getRoleUserReqVO.setRoleIdList(qryList);
        getRoleUserReqVO.setSearchKey(vo.getSearchKey());
        //批量查询用户清单
        List<SysRoleUserDTO> sysRoleUserDTOList = sysRoleDomain.getUsersByRoles(getRoleUserReqVO);
        Map<Long, RoleInfoResponseVO> tmpMap = new HashMap<>();
        for (SysRoleUserDTO sysRoleUserDTO : sysRoleUserDTOList) {
            RoleInfoResponseVO tmpRoleInfoResponseVO = null;
            if (tmpMap.containsKey(sysRoleUserDTO.getRoleId())) {
                tmpRoleInfoResponseVO = tmpMap.get(sysRoleUserDTO.getRoleId());
            } else {
                tmpRoleInfoResponseVO = new RoleInfoResponseVO();
                BeanUtils.copyProperties(sysRoleUserDTO, tmpRoleInfoResponseVO);
                List<UserInfoResVO> userList = new ArrayList<>();
                tmpRoleInfoResponseVO.setUserList(userList);
                tmpMap.put(sysRoleUserDTO.getRoleId(), tmpRoleInfoResponseVO);
            }
            if (StringUtils.isNotEmpty(vo.getUserName())) {
                if (sysRoleUserDTO.getUserName().contains(vo.getUserName())) {
                    UserInfoResVO tmpUserInfoResVO = new UserInfoResVO();
                    BeanUtils.copyProperties(sysRoleUserDTO, tmpUserInfoResVO);
                    tmpRoleInfoResponseVO.getUserList().add(tmpUserInfoResVO);
                    tmpRoleInfoResponseVO.setUserQty(tmpRoleInfoResponseVO.getUserQty() + 1);
                }
            }else if(StringUtils.isNotEmpty(vo.getSearchKey())){
                if ((sysRoleUserDTO.getUserName().contains(vo.getSearchKey())) || (sysRoleUserDTO.getEmployeeCode().contains(vo.getSearchKey()))) {
                    UserInfoResVO tmpUserInfoResVO = new UserInfoResVO();
                    BeanUtils.copyProperties(sysRoleUserDTO, tmpUserInfoResVO);
                    tmpRoleInfoResponseVO.getUserList().add(tmpUserInfoResVO);
                    tmpRoleInfoResponseVO.setUserQty(tmpRoleInfoResponseVO.getUserQty() + 1);
                }
            } else {
                tmpRoleInfoResponseVO.setUserQty(tmpRoleInfoResponseVO.getUserQty() + 1);
            }
        }
        for (RoleInfoResponseVO item : newPagerEntity.getDataList()) {
            RoleInfoResponseVO tmpPositionInfoResponseVO = tmpMap.get(item.getRoleId());
            if (null == tmpPositionInfoResponseVO) {
                continue;
            }
            item.setUserList(tmpPositionInfoResponseVO.getUserList());
            item.setUserQty(tmpPositionInfoResponseVO.getUserQty());
        }
        return BaseResult.buildSuccess(newPagerEntity);
    }

    /**
     * 根据用户信息查询角色列表
     *
     * @param vo 用户信息
     * @return 角色列表
     */
    public BaseResult<List<RoleInfoResponseVO>> selectRoleListByUserV1(SelectRoleListByUserReqVO vo) {
        if (null == vo) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (StringUtils.isEmpty(vo.getUserName())) {
            return BaseResult.buildError(BaseErrorCode.USER_NAME_IS_NULL.getCode(), BaseErrorCode.USER_NAME_IS_NULL.getMessage());
        }

        List<SysRoleUserDTO> sysRoleUserDTOList = sysUserRoleDomain.selectRoleListByUser(vo);
        List<RoleInfoResponseVO> roleInfoResponseVOList = new ArrayList<RoleInfoResponseVO>();
        if (CollectionUtils.isEmpty(sysRoleUserDTOList)) {
            return BaseResult.buildSuccess(roleInfoResponseVOList);
        }

        Map<String, RoleInfoResponseVO> roleInfoResponseVOMap = new HashMap<>();
        for (SysRoleUserDTO sysRoleUserDTO : sysRoleUserDTOList) {
            RoleInfoResponseVO tmpRoleInfoResponseVO = null;
            if (roleInfoResponseVOMap.containsKey(sysRoleUserDTO.getRoleId() + "")) {
                tmpRoleInfoResponseVO = roleInfoResponseVOMap.get(sysRoleUserDTO.getRoleId() + "");
            } else {
                tmpRoleInfoResponseVO = new RoleInfoResponseVO();
                tmpRoleInfoResponseVO.setRoleId(sysRoleUserDTO.getRoleId());
                tmpRoleInfoResponseVO.setRoleCode(sysRoleUserDTO.getRoleCode());
                tmpRoleInfoResponseVO.setRoleName(sysRoleUserDTO.getRoleName());
                List<UserInfoResVO> userList = new ArrayList<>();
                tmpRoleInfoResponseVO.setUserList(userList);
                roleInfoResponseVOMap.put(sysRoleUserDTO.getRoleId() + "", tmpRoleInfoResponseVO);
            }

            UserInfoResVO userInfoResVO = new UserInfoResVO();
            userInfoResVO.setUserId(sysRoleUserDTO.getUserId());
            userInfoResVO.setUserName(sysRoleUserDTO.getUserName());
            userInfoResVO.setUserAccount(sysRoleUserDTO.getUserAccount());
            userInfoResVO.setEmployeeCode(sysRoleUserDTO.getEmployeeCode());
            tmpRoleInfoResponseVO.getUserList().add(userInfoResVO);
        }

        roleInfoResponseVOList.addAll(roleInfoResponseVOMap.values());
        return BaseResult.buildSuccess(roleInfoResponseVOList);
    }

    @Override
    public BaseResult<Map<Long, String>> qryRoleNameMap(List<Long> vo) {
        if (org.springframework.util.CollectionUtils.isEmpty(vo)) {
            return BaseResult.buildSuccess(Collections.emptyMap());
        }
        Map<Long, SysRole> sysRoleMap = sysRoleDomain.qryRoleMapWithIsDeletedByIdList(vo);
        Map<Long, String> collect = sysRoleMap.entrySet().stream()
                .filter(map -> org.apache.commons.lang3.StringUtils.isNotEmpty(map.getValue().getRoleName()))
                .collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue().getRoleName(), (v1, v2) -> v2));
        return BaseResult.buildSuccess(collect);
    }

    @Override
    public BaseResult<com.alibaba.algo.cooperation.common.PagerEntity<UserRoleInfoResVO>> selectUserPageByRoleCondition(SelectUserListByRoleReqVO vo) {
        // 检查参数合法性
        if (null == vo) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (null == vo.getRoleId() && StringUtils.isEmpty(vo.getRoleCode()) && StringUtils.isEmpty(vo.getSearchKey())) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (null == vo.getPageIndex() || vo.getPageIndex() < 0) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getMsg());
        }
        if (null == vo.getPageSize() || vo.getPageSize() <= 0) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getMsg());
        }
        if (vo.getPageSize() > 10) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_SIZE_OVERSIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_OVERSIZE_ERROR.getMsg());
        }

        // 执行查询动作
        PagerEntity<UserRoleInfoResVO> pagerEntity = sysRoleDomain.selectUserPageByRoleCondition(vo);
        List<UserRoleInfoResVO> dataList = pagerEntity.getDataList();
        List<UserRoleInfoResVO> feignDatas = ConverterUtil.getInstance().mapAsList(dataList, UserRoleInfoResVO.class);
        com.alibaba.algo.cooperation.common.PagerEntity<UserRoleInfoResVO> feignPage
                = ConverterUtil.getInstance().map(pagerEntity, com.alibaba.algo.cooperation.common.PagerEntity.class);
        feignPage.setDataList(feignDatas);
        return BaseResult.buildSuccess(feignPage);
    }

    /**
     * 通过角色Id或Code查询角色基本详情
     * @param paramVO
     * @return
     */
    @Override
    public BaseResult<RoleBaseInfoResponseVO> getRoleBaseInfoByIdOrCode(GetRoleBaseInfoReqVO paramVO) {
        // 检查参数合法性
        if (null == paramVO) {
            return BaseResult.buildError("参数不能为空");
        }
        if (StringUtils.isEmpty(paramVO.getAppCode())) {
            return BaseResult.buildError("应用编码不能为空");
        }
        if (null == paramVO.getRoleId() && StringUtils.isEmpty(paramVO.getRoleCode())) {
            return BaseResult.buildError("角色ID或角色编码必填其一");
        }
        // 执行查询
        RoleBaseInfoResponseVO resultVO = sysRoleDomain.getRoleBaseInfoByIdOrCode(paramVO);
        return null != resultVO ? BaseResult.buildSuccess(resultVO) : BaseResult.buildError("没查到数据");
    }

    /**
     * 根据角色Code员工工号租户Code判断是否有该角色
     * @param paramVO
     * @return
     */
    @Override
    public BaseResult<List<CheckRoleInfoResponseVO>> checkRoleByCodeAndEmployee(RoleEmployeeReqVO paramVO) {
        // 检查参数合法性
        if (null == paramVO) {
            return BaseResult.buildError("参数不能为空");
        }
        if (StringUtils.isEmpty(paramVO.getAppCode())) {
            return BaseResult.buildError("应用编码不能为空");
        }
        if (StringUtils.isEmpty(paramVO.getEmployeeCode())) {
            return BaseResult.buildError("员工工号不能为空");
        }
        if (ObjectUtils.isEmpty(paramVO.getRoleCodeList())) {
            return BaseResult.buildError("角色编码集合不能为空");
        }
        if (paramVO.getRoleCodeList().size() > 300){
            return BaseResult.buildError("角色编码集合过大，不能超过300个");
        }
        List<CheckRoleInfoResponseVO> result = sysRoleDomain.checkRoleByCodeAndEmployee(paramVO);
        return BaseResult.buildSuccess(result);
    }

    @Override
    public BaseResult insertUserByRoleId(UpdateRoleVO updateRoleVO){
        if(updateRoleVO==null){
            return BaseResult.buildError("参数不能为空");
        }
        if(ObjectUtils.isEmpty(updateRoleVO.getId())){
            return BaseResult.buildError("角色id不能为空");
        }
        if(ObjectUtils.isEmpty(updateRoleVO.getUserIdList())){
            return BaseResult.buildError("授权用户不能为空");
        }
        sysUserRoleDomain.updateRelatedByRoleIdV2(updateRoleVO.getId(),updateRoleVO.getUserIdList(),0);
        return BaseResult.buildSuccess();
    }
}
